package com.elli0tt.config;

import com.elli0tt.pojo.Configuration;
import com.elli0tt.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @author elli0tt
 * @version 1.0
 * @className XMLMapperBuilder.java
 * @description Mapper.xml 解析器
 * @createTime 2020-08-28 21:58:14
 */
public class XMLMapperBuilder {
    /** 数据配置信息对象 */
    private final Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 解析 mapper.xml 并将信息添加到 {@link Configuration} 中的 mappedStatementMap 中
     *
     * @param inputStream mapper.xml 字节输入流对象
     * @throws Exception
     */
    public void parse(InputStream inputStream) throws Exception {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        addMappedStatement(rootElement, namespace, "select");
        addMappedStatement(rootElement, namespace, "insert");
        addMappedStatement(rootElement, namespace, "update");
        addMappedStatement(rootElement, namespace, "delete");
    }

    /**
     * 根据 sql 语句的类型将 mapper.xml 中对应类型的语句封装到 {@link MappedStatement} 中并添加到 mappedStatementMap
     *
     * @param rootElement mapper.xml 根标签元素
     * @param namespace mapper 命名空间
     * @param sqlCommandType sql 语句命令类型 select,insert,update,delete
     * @throws ClassNotFoundException
     */
    private void addMappedStatement(Element rootElement, String namespace, String sqlCommandType) throws ClassNotFoundException {
        List<Element> elements = rootElement.selectNodes(sqlCommandType);
        if (elements == null || elements.isEmpty()) {
            return ;
        }
        for (Element element : elements) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            Class<?> returnTypeClass = getClass(resultType);
            String parameterType = element.attributeValue("parameterType");
            Class<?> parameterTypeClass = getClass(parameterType);
            String sqlText = element.getTextTrim();

            MappedStatement mappedStatement = new MappedStatement(id, returnTypeClass, parameterTypeClass, sqlText);

            String statementId = namespace + "." + id;
            configuration.getMappedStatementMap().put(statementId, mappedStatement);
        }
    }

    /**
     * 根据类的全路径获取类对象
     *
     * @param className
     * @return
     * @throws ClassNotFoundException
     */
    private Class<?> getClass(String className) throws ClassNotFoundException {
        if (className == null || className.isEmpty()) {
            return null;
        }
        return Class.forName(className);
    }
}
